package com.openfire.client.demo.job;

import java.util.concurrent.CyclicBarrier;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;
import org.jivesoftware.smack.chat.ChatManagerListener;
import org.jivesoftware.smack.chat.ChatMessageListener;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager;
import org.jivesoftware.smackx.receipts.DeliveryReceiptManager.AutoReceiptMode;

import com.openfire.client.demo.listener.OpenfireConnectionListener;

/**
 * TODO: 增加描述
 * 
 * @author wei.ss
 * @date 2016-1-19 下午5:21:54
 * @version 1.0.0 
 * @copyright wonhigh.net.cn 
 */
public class UserConnectionJob implements Runnable {

	private String username;
	private String password;
	private XMPPTCPConnectionConfiguration configuration;
	private CyclicBarrier barrier;
	
	public UserConnectionJob(String username, String password, 
			XMPPTCPConnectionConfiguration configuration, CyclicBarrier barrier) {
		super();
		this.username = username;
		this.password = password;
		this.configuration = configuration;
		this.barrier = barrier;
	}

	@Override
	public void run() {
		AbstractXMPPConnection connection = null;
		try {
			try {
				connection = new XMPPTCPConnection(configuration);
				
				connection.addConnectionListener(new OpenfireConnectionListener());
				connection.setPacketReplyTimeout(Long.MAX_VALUE);
				connection.connect();
				System.out.println("before login: " + username);
				connection.login(username, password);
				
				// PingManager pingManager = PingManager.getInstanceFor(connection);
				// pingManager.setPingInterval(5);
				// pingManager.
				// 自动处理回执消息
				DeliveryReceiptManager.getInstanceFor(connection).setAutoReceiptMode(AutoReceiptMode.always);
				
				System.out.println(username + " login ok!");
				ChatManager chatManager = ChatManager.getInstanceFor(connection);
				chatManager.addChatListener(new ChatManagerListener() {
					@Override
					public void chatCreated(Chat chat, boolean createdLocally) {
						chat.addMessageListener(new ChatMessageListener() {

							@Override
							public void processMessage(Chat chat, Message message) {
								String body = message.getBody();
								if (body != null) {
									System.out.println("接收到消息: " + body);
								}
							}
						});
					}
				});
			} catch (Exception e) {
			}
			
			barrier.await();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					System.in.read();
					connection.disconnect();
				} catch (Exception e) {
				}
			}
		}
	}

}